import 'dart:convert';

import 'package:flutter_provider_demo/commons/log.dart';
import 'package:http/http.dart' as http;

class HttpClient {
  static final Log _log = Log();
  static final HttpClient _instance = HttpClient._();
  factory HttpClient() => _instance;
  HttpClient._() {
    _client = http.Client();
  }

  static final int _timeout = 5000;
  late final http.Client _client;

  Future<http.Response> get(
    String path, {
    Map<String, String>? headers,
    int? timeout,
  }) async {
    _log.debug('GET $path');
    final url = Uri.parse(path);
    return await _client
        .get(
          url,
          headers: headers,
        )
        .timeout(Duration(milliseconds: timeout ?? _timeout));
  }

  Future<http.Response> post(
    String path, {
    Map<String, String>? headers,
    required Map<String, dynamic> body,
    int? timeout,
  }) async {
    _log.debug('POST $path');
    final url = Uri.parse(path);
    return await _client
        .post(
          url,
          headers: {...?headers, 'Content-Type': 'application/json'},
          body: jsonEncode(body),
        )
        .timeout(Duration(milliseconds: timeout ?? _timeout));
  }
}
